package org.changchen.fgt.controller;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.changchen.fgt.config.SourceApiConfig;
import org.changchen.fgt.constant.GlobalConstants;
import org.changchen.fgt.dto.ApiInfo;
import org.changchen.fgt.dto.VideoDetail;
import org.changchen.fgt.dto.VideoInfo;
import org.changchen.fgt.service.FilmService;
import org.changchen.fgt.utils.ApplicationContextUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import lombok.extern.slf4j.Slf4j;

@Controller
@RequestMapping(value = "/video")
@Slf4j
public class FilmController {
	
	@Resource
	private FilmService filmService;
	
	
	@GetMapping(value = "/list")
	@ResponseBody
	public List<VideoInfo> list(@RequestParam(value = "wd") String word){
		return filmService.getVideoList(word);
	}
	
	
	@GetMapping(value = "/detail")
	@ResponseBody
	public VideoDetail detail(String code, Integer vodId) {
		return filmService.getVideoDetail(code, vodId);
	}
	
	@GetMapping(value = "/play")
	public ModelAndView play(String code, Integer vodId, Integer ep, Float time) {
		
		String page = "player";
		// 移动端访问
		if((boolean) ApplicationContextUtil.get(GlobalConstants.ISMOBILE)) {
			page = "mobile/player";
		}
		
		ModelAndView model = new ModelAndView(page);		
		model.addObject("code", code);
		ApiInfo apiInfo = SourceApiConfig.SRC_CONFIG.get(code);
		if(apiInfo == null) {
			log.error("资源{}暂时无效，请稍后访问...", code);
		} else {
			model.addObject("from", apiInfo.getName());
		}
		model.addObject("vodId", vodId);
		model.addObject("epIdx", ep == null || ep < 0 ? 0 : ep);
		model.addObject("time", time == null ? 0 : time);
		model.addObject("mobile", ApplicationContextUtil.get(GlobalConstants.ISMOBILE));
		
		return model;
	}
	
	
	@GetMapping(value = "/play/load")
	@ResponseBody
	public VideoDetail playLoad(String code, Integer vodId) {
		return filmService.getVideoDetail(code, vodId);
	}
	
	
	@GetMapping(value = "/download")
	public ModelAndView download(String code, Integer vodId, HttpServletResponse response) {		
		return filmService.downloadM3u8(code, vodId, response);
	}
	
	
	
}
